import Image

class SpriteItem(object):
  def __init__(self):
    self.bounds = None
    self.image = None
    self.filename = None
    self.cssclass = None
  
  def __repr__(self):
    return "%s%s" % (self.filename, self.bounds)

  def DrawTo(self, img):
    img.paste (self.image, self.bounds.ltrb)

  def CssRule(self, imgfile):
    return ".%(rule)s { background: transparent url(%(file)s) -%(x)dpx -%(y)dpx no-repeat; width: %(w)dpx; height: %(h)dpx; }" % {
      'rule' : self.cssclass,
      'file': imgfile,
      'x' : self.bounds.l,
      'y' : self.bounds.t,
      'w' : self.bounds.w,
      'h' : self.bounds.h,
      }

class SpriteBuilder(object):
  def __init__(self):
    self.sprites = []
    self.xsize = 0
    self.ysize = 0
  
  def AddSprite(self, spriteitem):
    self.sprites.append (spriteitem)

    self.xsize = max(self.xsize, spriteitem.bounds.r)
    self.ysize = max(self.ysize, spriteitem.bounds.b)

  def ValidateLayout(self):
    def enumwithpos(l):
      i = 0
      for e in l:
        yield i, e
        i += 1
    
    def allpairs(l):
      for i, l_i in enumwithpos(l):
        for j, l_j in enumwithpos(l):
          if i > j:
            yield l_i, l_j

    # this is a naive algorithm... oh well
    for i, j in allpairs(self.sprites):
      if i.bounds.intersects (j.bounds):
        raise Exception ("%s intersects %s" % (i, j))

  def Draw(self):
    output = Image.new("RGBA", (self.xsize, self.ysize))

    for s in self.sprites:
      s.DrawTo (output)

    return output

  def HtmlDemo(self, imgfile):

    r = ""
    r += """
    <html><head></head><body>
    """

    for s in self.sprites:
      r += "<h1>%s</h1>" % s.filename
      r += "<style>%s</style>" % s.CssRule(imgfile)
      r += "<p><pre>%s</pre></p>" % s.CssRule(imgfile)
      r += "<div class='%s'></div>" % s.cssclass


    r += """
    </body>
    """

    return  r
